import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { WebSocketSession,SocketMessage } from '../entity'
import emitter from '@/utils/emitter';
import {useCurrentUserStore} from '@/modules/security/stores/currentUserStores'


export const webSocketStore = defineStore('webSocketSession', () => {
  const userStore = useCurrentUserStore()
  const session = ref<WebSocketSession | null>(null);
  
  // 连接
  function connectWebSocket(){
    if (userStore.isLoggedIn()) {
        const username = userStore.currentUser?.user.username||"";
        const token = userStore.currentUser?.Authorization.replace('Bearer ', '')||""
        const wsUrl = getWsUrl(username,token)
        const wsConnect = new WebSocket(wsUrl)
        let wsConnected = false;
        
        // 连接
        wsConnect.onopen = () => {
          wsConnected = true
          session.value = {wsConnect,wsConnected}
        }
        // 关闭
        wsConnect.onclose = () => {
            wsConnected = false
            disconnectWebSocket()
        }
        // 收到消息
        wsConnect.onmessage = (event) => {
            const message = JSON.parse(event.data);
            handleMessage(message as SocketMessage)
        }
        
        // 异常
        wsConnect.onerror = (error) => {
          console.error(error)
          wsConnected = false
        }

    }
  }
  // 关闭连接
  function disconnectWebSocket() {
    if (session.value!=null) {
        if(session.value.wsConnect!=null){
            session.value.wsConnect.close()
            session.value.wsConnect = null;
        }
        session.value.wsConnected = false
    }
  }
  // 重新连接
  function reconnectWebSocket() {
    disconnectWebSocket()
    connectWebSocket()
  }
  // 发送消息
  function handleMessage(message: SocketMessage){
    emitter.emit(`/ws${message.path}`, message.message);
  }
  function getWsUrl(username: string, token: string) {
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
      const host = window.location.host  // 这会获取当前域名和端口
      return `${protocol}//${host}${import.meta.env.VITE_WS_BASE_API}/${username}/${token}`
  }
  // 订阅消息
  function subMessage(path: string, callback: (message: string) => void){
    // 注册事件处理器
    const handler = (event: unknown) => {
        callback(event as string);
    };
    emitter.on(`/ws${path}`, handler);
  }
  // 关闭订阅
  function unSubMessage(path: string,){
    emitter.off(`/ws${path}`);
  }

  return { session,connectWebSocket,disconnectWebSocket,reconnectWebSocket,subMessage,unSubMessage}
})  